// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, use_build_context_synchronously
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGButton.dart';
import 'dart:math';

class QGInitiatePurchasePage extends StatefulWidget {
  dynamic args;
  QGInitiatePurchasePage({super.key, this.args});
  @override
  State<QGInitiatePurchasePage> createState() => QGInitiatePurchasePageState();
}

class QGInitiatePurchasePageState extends State<QGInitiatePurchasePage> {
  int count = 1;
  String price = "--";
  dynamic data;
  final decimal = Decimal.parse;

  var countController = TextEditingController();
  var priceController = TextEditingController();

  @override
  void initState() {
    super.initState();
    data = widget.args;
    countController.text = "$count";

    countController.addListener(() {
      var ret = int.tryParse(countController.text);
      if (ret is int) {
        count = ret;

        if (count > 100) {
          countController.text = "99";
        } else if (count < 1) {
          countController.text = "1";
        }

        count = min(99, count);
        count = max(1, count);

        if (priceController.text.isEmpty) {
          return;
        }
        updatePrice();
      }
    });

    priceController.addListener(() {
      price = priceController.text;
      setState(() {});

      if (priceController.text.isEmpty) {
        price = "--";
        return;
      }
      updatePrice();
    });
  }

  @override
  Widget build(BuildContext context) {
    return QGScaffold(
        title: '发起求购',
        bgColor: Color(0xFFF8F8F6),
        body: GestureDetector(
          onTap: () {
            unfocus(context);
          },
          child: Column(
            children: [
              Expanded(
                child: Stack(
                  children: [
                    Padding(
                      padding: EdgeInsets.all(10.rpx),
                      child: ListView(
                        children: [
                          Column(
                            children: [
                              buildHeader(),
                              SizedBox(height: 10.rpx),
                              buildExtra(),
                              SizedBox(height: 65.rpx + max(10, kSafeBottom)),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Positioned(
                      bottom: 0,
                      left: 0,
                      right: 0,
                      child: buildBottom(),
                    )
                  ],
                ),
              ),
            ],
          ),
        ));
  }

  buildHeader() {
    return Container(
      padding: EdgeInsets.all(15.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xFFFFFFFF),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(6.rpx),
                child: QGImage(
                    url: data?["thumb_img"], width: 80.rpx, height: 80.rpx),
              ),
              SizedBox(width: 15.rpx),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    buildText(data?["name"] ?? "", 16.rpx, FontWeight.bold,
                        Color(0xFF111111)),
                    SizedBox(height: 15.rpx),
                    buildCount()
                  ],
                ),
              ),
            ],
          ),
          SizedBox(height: 20.rpx),
          buildText("求购价格", 14.rpx, FontWeight.bold, Color(0xFF111111)),
          SizedBox(height: 10.rpx),
          buildPrice(),
        ],
      ),
    );
  }

  buildText(text, size, weight, color) {
    return Text(
      text,
      style: TextStyle(color: color, fontSize: size, fontWeight: weight),
    );
  }

  buildCount() {
    return Row(
      children: [
        GestureDetector(
          onTap: onSub,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2.rpx),
              color: Color(0xFFDDDDDD),
            ),
            alignment: Alignment.center,
            width: 20.rpx,
            height: 20.rpx,
            child: Text(
              '-',
              style: TextStyle(
                  color: Color(0xFF111111),
                  fontSize: 15.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        ),
        SizedBox(
          width: 70.rpx,
          child: TextField(
            textAlign: TextAlign.center,
            controller: countController,
            keyboardType: TextInputType.number,
            textInputAction: TextInputAction.done,
            cursorColor: Color(0xFF111111),
            style: TextStyle(
                color: Color(0xFF111111),
                fontSize: 16.rpx,
                fontWeight: FontWeight.normal),
            decoration: const InputDecoration(
              enabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none,
            ),
          ),
        ),
        GestureDetector(
          onTap: onAdd,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2.rpx),
              color: Color(0xFFDDDDDD),
            ),
            alignment: Alignment.center,
            width: 20.rpx,
            height: 20.rpx,
            child: Text(
              '+',
              style: TextStyle(
                  color: Color(0xFF111111),
                  fontSize: 15.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        ),
      ],
    );
  }

  buildPrice() {
    return Container(
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(width: 0.5.rpx, color: Color(0xFFEAEAEA)))),
      child: Row(
        children: [
          SizedBox(
            width: 26.rpx,
            child: Text(
              '￥',
              style: TextStyle(
                  color: Color(0xFF111111),
                  fontSize: 16.rpx,
                  fontWeight: FontWeight.bold),
            ),
          ),
          Expanded(
            child: TextField(
                textAlign: TextAlign.start,
                controller: priceController,
                keyboardType:
                    const TextInputType.numberWithOptions(decimal: true),
                textInputAction: TextInputAction.done,
                cursorColor: Color(0xFF111111),
                style: TextStyle(
                    color: Color(0xFF111111),
                    fontSize: 16.rpx,
                    fontWeight: FontWeight.bold),
                decoration: InputDecoration(
                  hintText: "不得低于${data?["ask_price_limit"]}",
                  hintStyle: TextStyle(color: Color(0xFF999999)),
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none,
                )),
          ),
          SizedBox(width: 50.rpx),
        ],
      ),
    );
  }

  buildExtra() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Colors.white,
      ),
      padding: EdgeInsets.all(15.rpx),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Expanded(
            child: Text(
              """求购说明
1.如果自发起求购订单后，一周内没有成交，将会自动退款。
2.预付成功后，可在“我的-求购订单”中取消订单。
3.成交顺序以发起求购成功的时间、顺序成交。
4.求购期间成交，无法撒销。""",
              style: TextStyle(
                  height: 1.6,
                  color: Color(0xFFb8b8b8),
                  fontSize: 11.rpx,
                  fontWeight: FontWeight.bold),
            ),
          ),
        ],
      ),
    );
  }

  buildBottom() {
    return Container(
      padding: EdgeInsets.only(
          left: 10.rpx,
          right: 10.rpx,
          bottom: max(10, kSafeBottom),
          top: 10.rpx),
      decoration: BoxDecoration(
        color: Color(0xFFFFFFFF),
      ),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Flexible(
          child: Text(
            "￥$price",
            style: TextStyle(
                color: Color(0xFF111111),
                fontSize: 24.rpx,
                fontWeight: FontWeight.bold),
          ),
        ),
        Flexible(
          child: Container(
              alignment: Alignment.center,
              height: 44.rpx,
              width: 200.rpx,
              child: QGButton(
                title: "预付",
                onTap: onPay,
              )),
        )
      ]),
    );
  }

  onAdd() {
    unfocus(context);
    count++;
    count = min(99, count);
    countController.text = "$count";
    if (mounted) setState(() {});

    if (priceController.text.isEmpty) {
      return false;
    }
    updatePrice();
  }

  onSub() {
    unfocus(context);
    count--;
    count = max(1, count);
    countController.text = "$count";
    if (mounted) setState(() {});

    if (priceController.text.isEmpty) {
      return false;
    }
    updatePrice();
  }

  updatePrice() {
    price =
        (decimal(priceController.text) * decimal("$count")).toStringAsFixed(2);
    if (mounted) {
      setState(() {});
    }
  }

  onPay() {
    if (priceController.text.isEmpty) {
      toast("请输入求购价格");
      return;
    }

    unfocus(context);

    var param = {};
    param['pid'] = data?["pid"];
    param['num'] = count;
    param['price'] = priceController.text;
Map<String, dynamic> stringMap = param.cast<String, dynamic>();

    Network.post(url_ask_addOrder, data: stringMap, context: context)
        .then((res) async {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      var url = res.data["pay_url"];
      if (url is String && !url.startsWith("http")) {
        url = url;
      }
      if (url is! String || !url.startsWith("http")) {
        toast("数据解析失败");
        return;
      }

      Navigator.of(context)
          .pushReplacementNamed(PageQGPayWebView, arguments: url);
    });
  }
}
